package com.dq.service.sys.user.impl;

import com.dq.context.Constant;
import com.dq.controller.in.user.SysUserQuery;
import com.dq.domain.sys.user.user.BossUser;
import com.dq.exception.customException.AdminException;
import com.dq.controller.in.user.OrgUserQuery;
import com.dq.controller.in.base.BaseAdminQuery;
import com.dq.domain.base.impl.BaseDaoImpl;
import com.dq.domain.org.Org;
import com.dq.domain.sys.role.SysRole;
import com.dq.domain.sys.role.SysUserRole;
import com.dq.domain.sys.user.user.OrgUser;
import com.dq.domain.sys.user.user.base.SysUser;
import com.dq.repository.BaseRepositories;
import com.dq.service.org.OrgService;
import com.dq.service.sys.user.BossUserService;
import com.dq.service.sys.user.OrgUserService;
import com.dq.vo.ListDataVo;
import com.dq.vo.Vo;
import com.dq.vo.baseVo.VO;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author liuhui
 * @date 2019/12/3 0003 10:00:36
 */
@Service
public class OrgUserServiceImpl extends BaseRepositories implements OrgUserService {
    @Autowired
    private OrgService orgService;
    @Autowired
    private BossUserService bossUserService;

    /**
     * 查询列表 条件
     */
    @Override
    public Map<String, Object> getOrgListHql(OrgUserQuery orgUserQuery) throws AdminException {
        Map<String, Object> query = orgUserQuery.parseMap();
        if(orgUserQuery.getOrgId() != null) {
            query.put("section_id", orgUserQuery.getOrgId());
            query.remove("orgId");
        }else {
            // 只显示负责门店信息
            List<Org> orgList = orgService.getListAllByUser();
            if(orgList == null || orgList.size() <= 0) {
                throw new AdminException("此账号无负责门店");
            }
            query.put("section" + BaseDaoImpl.inSqlStr, orgList);
        }

        if(StringUtils.isNotBlank(orgUserQuery.getUserRealcName())) {
            query.put("userRealcName" + BaseDaoImpl.likeSqlStr, BaseAdminQuery.likeSql(orgUserQuery.getUserRealcName()));
            query.remove("userRealcName");
        }

        if(StringUtils.isNotBlank(orgUserQuery.getSearchBox())) {
            Map<String, Object> keyQuery = new HashMap<>(16);

            keyQuery.put("userRealcName" + BaseDaoImpl.likeSqlStr, BaseAdminQuery.likeSql(orgUserQuery.getSearchBox()));
            keyQuery.put("username" + BaseDaoImpl.likeSqlStr, BaseAdminQuery.likeSql(orgUserQuery.getSearchBox()));

            query.put("keyQuery" + BaseDaoImpl.orAndSqlStr, keyQuery);
            query.remove("searchBox");
        }
        if(orgUserQuery.getTimeBegin() != null) {
            query.put("createTime" + BaseDaoImpl.gteSqlStr, orgUserQuery.getTimeBegin());
            query.remove("timeBegin");
        }
        if(orgUserQuery.getTimeEnd() != null) {
            query.put("createTime" + BaseDaoImpl.lteSqlStr, orgUserQuery.getTimeEnd());
            query.remove("timeEnd");
        }
        return query;
    }


    /**
     * 保存门店账号/关联门店角色
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public OrgUser save(OrgUser orgUser) throws AdminException {
        if(orgUser.getMobile() == null) {
            orgUser.setMobile(orgUser.getUsername());
        }

        orgUser = initObject(orgUser);

        orgUser.setPassword(sysUserService.getPassword(orgUser.getPassword()));

//        List<SysUser> userListByUsername = dao.findBySql(SysUser.class, String.format("select u.* from sys_user u where u.username = '%s'", orgUser.getUsername()));
        SysUser sysUser = sysUserRepository.findByUsername(orgUser.getUsername());
        if (null != sysUser) {
            throw new AdminException("该账号已存在");
        }
        if(StringUtils.isNotBlank(orgUser.getMobile())) {
//            List<SysUser> userListByMobile = dao.findBySql(OrgUser.class, String.format("select u.* from sys_user u where u.mobile = '%s' and dtype = 'OrgUser'", orgUser.getMobile()));
            OrgUser byMobile = orgUserRepository.findByDeletedFalseAndMobile(orgUser.getMobile());
            if(byMobile != null) {
                throw new AdminException("手机号已存在");
            }
        }

        // 门店用户 角色
        List<SysRole> roles = sysRoleRepository.findByDeletedFalseAndCodeOrderByCreateTimeDesc(Constant.ROLE_CODE_LIST.get(4));
        if(roles == null || roles.size() <= 0) {
            throw new AdminException("门店角色获取异常");
        }

        dao.saveOrModify(orgUser);

        SysUserRole userRole = new SysUserRole();
        userRole.setSysUser(orgUser);
        userRole.setSysRole(roles.get(0));
        userRole = sysRoleService.initObjectUserRole(userRole);
        dao.saveOrModify(userRole);

        return orgUser;
    }

    /**
     * 对象初始化
     */
    @Override
    public OrgUser initObject(OrgUser orgUser) throws AdminException {
        if(StringUtils.isBlank(orgUser.getCardNo())) {
            orgUser.setCardNo(OrgUser.generyDatetimeAndRandomNum(Constant.ORDERS_SUFF_COUNT));
        }
        if(orgUser.getStatus() == null) {
            orgUser.setStatus(SysUser.Status.on);
        }

        ifObject(orgUser);

        orgUser.setVersion(Constant.VERSION_VALUE);
        orgUser.setDeleted(false);
        orgUser.setCreateTime(System.currentTimeMillis());
        orgUser.setLastModifyTime(System.currentTimeMillis());

        SysUser user = sysUserService.getUser();
        orgUser.setCreateUser(user);
        orgUser.setUpdateUser(user);

        return orgUser;
    }

    @Override
//    @Transactional(rollbackFor = Exception.class)
    public OrgUser update(OrgUser orgUser) throws AdminException {
        ifObject(orgUser);

        // 登录名 判断重复
        SysUser sysUser = sysUserRepository.findByUsername(orgUser.getUsername());
        if (null != sysUser && !sysUser.getId().toString().equals(orgUser.getId().toString())) {
            throw new AdminException("该账号已存在");
        }
        if(StringUtils.isBlank(orgUser.getMobile())) {
            orgUser.setMobile(orgUser.getUsername());
        }
        if(StringUtils.isNotBlank(orgUser.getMobile())) {
            OrgUser byMobile = orgUserRepository.findByDeletedFalseAndMobile(orgUser.getMobile());
            if(byMobile != null) {
                if(!byMobile.getId().toString().equals(orgUser.getId().toString())) {
                    throw new AdminException("手机号已存在");
                }
            }
        }

        SysUser user = sysUserService.getUser();
        orgUser.setUpdateUser(user);

        orgUserRepository.save(orgUser);

        return orgUser;
    }

    private void ifObject(OrgUser orgUser) throws AdminException {
        if(orgUser.getSection() == null || orgUser.getSection().getId() == null) {
            throw new AdminException("所属门店为空");
        }
        if(StringUtils.isBlank(orgUser.getUserRealcName())) {
            throw new AdminException("用户昵称为空");
        }
        if(StringUtils.isBlank(orgUser.getUsername())) {
            throw new AdminException("用户 账号 为空");
        }
        if(StringUtils.isBlank(orgUser.getPassword())) {
            throw new AdminException("用户 密码 为空");
        }
        if(StringUtils.isBlank(orgUser.getCardNo())) {
            throw new AdminException("编号 为空");
        }
        if(orgUser.getStatus() == null) {
            throw new AdminException("状态 为空");
        }
    }

    /**
     * 根据角色获取单个门店的用户, user->bossuser
     */
    @Override
    public List<BossUser> getOrgUserListByRoles(SysUserQuery sysUserQuery, int... index) {
        if(sysUserQuery.getOrgId() == null) {
            sysUserQuery.setOrgId(sysUserService.getUserInSection().getSection().getId());
        }

        return bossUserService.getBossUserListByRoles(sysUserQuery, index);
    }
    @Override
    public Long getOrgUserCountByRoles(SysUserQuery sysUserQuery, int... index) {
        if(sysUserQuery.getOrgId() == null) {
            sysUserQuery.setOrgId(sysUserService.getUserInSection().getSection().getId());
        }

        return bossUserService.getBossUserCountByRoles(sysUserQuery, index);
    }
}
